package com.open.capacity.form.controller;


import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.form.model.FormDbSource;
import com.open.capacity.form.service.FormDbSourceService;
import com.open.capacity.form.service.FormDbTableService;
import com.open.capacity.utils.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bouncycastle.math.ec.NafL2RMultiplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 数据源管理
 */
@RestController
@Api(tags = "数据源模块api")
public class FormDbSourceController {


    @Autowired
    private FormDbSourceService dbSourceService;

    @Autowired
    private FormDbTableService dbTableService;


    /**
     * 查询数据源
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('dbSource:get/dbSources')")
    @ApiOperation(value = "查询数据源")
    @GetMapping("/dbSources")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result<List<FormDbSource>> findDbSources(@RequestParam Map<String, Object> params) {
        List<FormDbSource> list = dbSourceService.findDbSources(params);
        return Result.succeed(list);
    }


    /**
     * 查询数据源
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取数据源")
    @PreAuthorize("hasAuthority('dbSource:get/dbSources/{id}')")
    @GetMapping("/dbSources/{id}")
    public Result<FormDbSource> findDbSourceById(@PathVariable(value = "id") String id) {
        FormDbSource source = dbSourceService.findById(id);
        return Result.succeed(source);
    }

    @ApiOperation(value = "获取数据源名称")
    @PreAuthorize("hasAuthority('post:get/dbSources/getName')")
    @GetMapping("/dbSources/getName")
    public Result getdbSourceName(@RequestParam(value = "keyValue") String keyValue) {
        FormDbSource source = dbSourceService.findByCode(keyValue);
        return Result.succeed(source == null ? "" : source.getName(), "获取成功！");
    }


    /**
     * 获取表字段集合信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取表字段集合信息")
    @PreAuthorize("hasAuthority('dbSource:get/dbSources/{id}/columnNames')")
    @GetMapping("/dbSources/{id}/columnNames")
    public Result<List<String>> getColumnNames(@PathVariable(value = "id") String id) {
        FormDbSource source = dbSourceService.findById(id);
        List<Map<String, Object>> data = dbTableService.findData(source.getDbId(), "(" + source.getSqlScript() + ") limit 1", new HashMap<>());
        return Result.succeed(CollectionUtil.GetMapKey(data));
    }

    /**
     * 获取数据源数据
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取数据源数据")
    @PreAuthorize("hasAuthority('dbSource:get/dbSources/{id}/findData')")
    @GetMapping("/dbSources/{id}/findData")
    public PageResult<Map<String, Object>> findData(@PathVariable(value = "id") String id, @RequestParam Map params) {
        FormDbSource source = dbSourceService.findById(id);
        PageResult<Map<String, Object>> data = dbTableService.pageData(source.getDbId(), "(" + source.getSqlScript() + ")", params);
        return data;
    }


    /**
     * 数据源新增或者更新
     *
     * @param sysDbSource
     * @return
     */
    @PreAuthorize("hasAnyAuthority('dbSource:post/dbSources','dbSource:put/dbSources')")
    @ApiOperation(value = "保存数据源")
    @PostMapping("/dbSources/saveOrUpdate")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody FormDbSource sysDbSource, String keyValue) {
        return dbSourceService.saveOrUpdate(sysDbSource, keyValue);
    }


    /**
     * 删除数据源
     * delete /dbSources/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('dbSource:delete/dbSources/{id}')")
    @ApiOperation(value = "删除数据源")
    @DeleteMapping("/dbSources/{id}")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            dbSourceService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("操作失败");
        }
    }

}
